package com.smfx.yxt.controller.teacher;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smfx.yxt.common.AppUser;
import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.MenuConst;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.LeaveStatus;
import com.smfx.yxt.common.enums.RelationType;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.common.enums.WorkApprovalType;
import com.smfx.yxt.controller.BaseController;
import com.smfx.yxt.model.AttachmentList;
import com.smfx.yxt.model.Grid;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.model.TeacherLeave;
import com.smfx.yxt.page.OrderBy;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.TeacherLeaveReqVO;
import com.smfx.yxt.service.IAttachmentListService;
import com.smfx.yxt.service.ITeacherLeaveService;
import com.smfx.yxt.service.IWorkApprovalService;
import com.smfx.yxt.utils.DateUtil;
import com.smfx.yxt.view.TeacherLeaveView;
import com.smfx.yxt.vo.TeacherLeaveQueryVO;

@RequestMapping(Const.TEACHER_ROLE + MenuConst.TEACHER_LEAVE)
@Controller
public class TeacherLeaveController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(TeacherLeaveController.class);
	@Autowired
	private ITeacherLeaveService teacherLeaveService;
	@Autowired
	private IAttachmentListService attachmentListService;
	
	/**
	 * 老师请假页面
	 * @return
	 */
	@RequestMapping(value = {"","/"})
	public String teacherLeave(Model model){
		AppUser appUser = getAppUser();
		if(teacherLeaveService.isTeacherLeaveApprover(appUser.getTeacher().getId())) {
			return "teacherLeave/approverList";
		}
		if(teacherLeaveService.isTeacherLeaveCcer(appUser.getTeacher().getId())) {
			model.addAttribute("isCcer", true);
		}
		return "teacherLeave/list";
	}
	
	@RequestMapping("publish")
	public String publish(Model model) {
		model.addAttribute("relationType", RelationType.TEACHER_LEAVE.getCode());
		model.addAttribute("approvalType", WorkApprovalType.TEACHER_LEAVE.getCode());
		return "teacherLeave/publish";
	}
	
	@RequestMapping("agreeList")
	public String agreeList(Model model) {
		return "teacherLeave/agreeList";
	}
	
	@RequestMapping("detail/{id}")
	public String publish(Model model,@PathVariable Integer id) {
		TeacherLeaveView teacherLeave = teacherLeaveService.selectViewById(id);
		model.addAttribute("detail", teacherLeave);
		return "teacherLeave/detail";
	}
	
	@RequestMapping("editor/{id}")
	public String edior(Model model,@PathVariable Integer id) {
		TeacherLeaveView teacherLeave = teacherLeaveService.selectViewById(id);
		if(teacherLeave.getIsAttach() == 1) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("type", RelationType.TEACHER_LEAVE.getCode());
			map.put("objId", teacherLeave.getId());
			List<AttachmentList> list = attachmentListService.queryAttachmentListByRelationId(map);
			model.addAttribute("attachList", list);
		}
		model.addAttribute("detail", teacherLeave);
		return "teacherLeave/editor";
	}
	
	@RequestMapping("page/query")
	@ResponseBody Object pageQuery(TeacherLeaveQueryVO vo) {
		try {
			Page<TeacherLeave> page = new Page<TeacherLeave>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("CREATE_TIME", "desc"));
			sorts.add(new OrderBy("UPDATE_TIME", "desc"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<TeacherLeave> list = teacherLeaveService.selectListByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return new RspResult(Status.SUCCESS, grid);
		} catch (Exception e) {
			logger.error("--pageQuery error={}", e);
		}
		return null;
	}
	
	/**
	 * 老师请假申请
	 * @param reqVO
	 * @return
	 */
	@RequestMapping("create")
	@ResponseBody Object teacherLeaveCreate(TeacherLeaveReqVO reqVO) {
		try {
			AppUser appUser = getAppUser();
			reqVO.setSchoolId(appUser.getTeacher().getSchoolId());
			reqVO.setTermId(getCurrentTerm().getId());
			reqVO.setTeacherId(appUser.getTeacher().getId());
			reqVO.setTeacherName(appUser.getTeacher().getName());
			if(reqVO.getIds() != null) {
				reqVO.setIsAttach(1);
			}
			teacherLeaveService.insert(reqVO);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---studentLeaveCreate error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	/**
	 * 修改教师请假信息
	 * @param record
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody Object updateLeave(TeacherLeave record) {
		try {
			TeacherLeave baseData = teacherLeaveService.selectByPrimaryKey(record.getId());
			if(!LeaveStatus.AUDIT_PENING.getCode().equals(baseData.getLeaveStatus()) || 
					(StringUtils.isNotBlank(baseData.getBackStatus()) && 
							!LeaveStatus.AUDIT_PENING.getCode().equals(baseData.getBackStatus()))) {
				return new RspResult(Status.EXPIRED_DATA);
			}
			record.setUpdateTime(new Date());
			teacherLeaveService.updateByPrimaryKeySelective(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---updateLeave error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("audit")
	@ResponseBody Object teacherStudentLeaveAudit(TeacherLeave record) {
		try {
			int result = teacherLeaveService.updateAudit(record);
			if(result > 0) {
				return new RspResult(Status.SUCCESS);
			}
		} catch (Exception e) {
			logger.error("---teacherStudentLeaveAudit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("cancel")
	@ResponseBody Object teacherLeaveCancel(Integer applyId){
		AppUser appUser = getAppUser();
		TeacherLeave leave = teacherLeaveService.selectByPrimaryKey(applyId);
		if(leave.getTeacherId().intValue() == appUser.getTeacher().getId().intValue()) {
			if(LeaveStatus.AUDIT_PENING.getCode().equals(leave.getLeaveStatus())) {
				leave.setUpdateTime(new Date());
				leave.setLeaveStatus(LeaveStatus.AUDIT_NO.getCode());
				teacherLeaveService.updateByPrimaryKeySelective(leave);
				return new RspResult(Status.SUCCESS);
			}else if(LeaveStatus.AUDIT_PENING.getCode().equals(leave.getBackStatus())) {
				leave.setUpdateTime(new Date());
				leave.setBackStatus(LeaveStatus.AUDIT_NO.getCode());
				teacherLeaveService.updateByPrimaryKeySelective(leave);
				return new RspResult(Status.SUCCESS);
			}
		}
		return new RspResult(Status.EXPIRED_DATA);
	}
	
	@RequestMapping("approver")
	@ResponseBody Object approver() {
		AppUser appUser = getAppUser();
		Integer grade = appUser.getTeacher().getGrade();
		if(grade != null && grade > 0) {
			List<TeacherInfo> list = teacherLeaveService.selectTeacherLeaveApprover(grade);
			return new RspResult(Status.SUCCESS, list);
		}
		return new RspResult(Status.FAIL.getCode(), "请先设置所任课年级");
	}
	
}
